package com.bone.spider.crawler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.webcollector.model.CrawlDatum;
import com.webcollector.plugin.net.OkHttpRequester;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author learnting
 * @date 2020-03-21
 */
public class DoubanHttpRequest extends OkHttpRequester {

  String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
  private Map<String, List<Cookie>> cookieStore;

  public DoubanHttpRequest(Map<String, List<Cookie>> cookieStore) {
    this.cookieStore = cookieStore;
  }

  @Override
  public OkHttpClient.Builder createOkHttpClientBuilder() {
    return super.createOkHttpClientBuilder()
      .cookieJar(new CookieJar() {
        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
          cookieStore.put(url.host(), cookies);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
          List<Cookie> cookies = cookieStore.get(url.host());
          return cookies != null ? cookies : new ArrayList<>();
        }
      });
  }

  // 每次发送请求前都会执行这个方法来构建请求
  @Override
  public Request.Builder createRequestBuilder(CrawlDatum crawlDatum) {
    // 这里使用的是OkHttp中的Request.Builder
    // 可以参考OkHttp的文档来修改请求头
    return super.createRequestBuilder(crawlDatum)
      .header("User-Agent", userAgent);
  }

}
